package com.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.junit.jupiter.api.Test;

import java.util.Calendar;
import java.util.HashMap;

public class SpirngJwt {


    /**
     *  生成token
     */
    @Test
    public void crete(){
         HashMap<String, Object> map = new HashMap<>();
         Calendar instance = Calendar.getInstance(); //日历
         instance.add(Calendar.SECOND,40);  //在20秒过后过期

         Object token = JWT.create()
                 .withHeader(map)   //header
                 .withClaim("userId", 24) //用户信息
                 .withClaim("username", "张三")
                 .withExpiresAt(instance.getTime())  //设置过期时间
                 .sign(Algorithm.HMAC256("!Q*@#$%&"));//签名
         System.out.println(token);
     }

    /**
     * 验证token 取信息
     */
    @Test
    public void  judgment(){
        //创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("!Q*@#$%&")).build();
        DecodedJWT jwt = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTQ2ODk4MzksInVzZXJJZCI6MjQsInVzZXJuYW1lIjoi5byg5LiJIn0.BrSidi7ksgzRSYvV9cqRN5xSD7USPfylZTzK7D6LW78");
        System.out.println(jwt.getClaim("userId").asInt()+"\n"+jwt.getClaim("username").asString());
        //获取 过期时长
        System.out.println(jwt.getExpiresAt());
    }
}
